package com.study.example.simpleclient.net;

import com.sparrow.socket.tcp.codec.Request;
import com.sparrow.common.util.JsonUtil;
import com.study.example.simpleclient.ClientMain;
import com.study.example.simpleclient.panel.LoginAuthPanel;
import com.study.example.simpleclient.panel.CreatePanel;
import com.study.example.simpleclient.panel.LoginPanel;
import com.sparrow.example_message.PacketId;
import com.sparrow.example_message.base.resp.RespCreatePacket;
import com.sparrow.example_message.base.resp.RespLoginAuthPacket;
import com.sparrow.example_message.base.resp.RespLoginPacket;
import com.study.example.simpleclient.panel.TestMsgPanel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import javax.swing.*;

public class SimpleClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Request request = (Request) msg;
        int msgId = request.getMsgId();
        Object msgPacket = request.getMsg();
        if (msgId == PacketId.Base.RESP_LOGIN_AUTH_PACKET) {
            RespLoginAuthPacket packet = (RespLoginAuthPacket) msgPacket;
            if (packet.getPlayerId() == 0) {
                ClientMain.showPanel(CreatePanel.class);
            } else {
                LoginPanel loginPanel = new LoginPanel(packet.getPlayerId(), packet.getName(), packet.getLevel());
                ClientMain.showPanel(loginPanel);
            }
        } else if (msgPacket instanceof RespCreatePacket) {
            RespCreatePacket packet = (RespCreatePacket) msgPacket;
            LoginPanel loginPanel = new LoginPanel(packet.getPlayerId(), packet.getName(), packet.getLevel());
            ClientMain.showPanel(loginPanel);
        } else if (msgPacket instanceof RespLoginPacket) {
            ClientMain.showPanel(TestMsgPanel.class);
        } else {
            TestMsgPanel.setText("收到消息:" + msgId
                    + "\n" + msgPacket.getClass().getSimpleName()+
                    "\n" + JsonUtil.toJSON(msgPacket));
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(null, "与服务器的连接已断开！", "连接中断", JOptionPane.WARNING_MESSAGE);
            // 可选：回到 AuthPanel 或其他 UI
            ClientMain.showPanel(LoginAuthPanel.class);
        });
        super.channelInactive(ctx);
    }
}

